<template>
  <div class="face-detect-container">
    <el-card title="人脸检测与信息展示">
      <!-- 摄像头预览与Canvas叠加（用于标记人脸） -->
      <div
        class="camera-wrapper"
        style="position: relative; width: 400px; margin: 0 auto"
      >
        <video
          ref="video"
          autoplay
          playsinline
          muted
          width="400"
          height="300"
          style="border: 1px solid #e6e6e6"
        ></video>
        <!-- Canvas：叠加绘制人脸框 -->
        <canvas
          ref="faceCanvas"
          width="400"
          height="300"
          style="position: absolute; top: 0; left: 0; pointer-events: none"
        ></canvas>
      </div>

      <!-- 识别信息展示 -->
      <div class="info-card" style="margin-top: 20px">
        <el-table :data="[detectInfo]" border style="width: 100%">
          <el-table-column
            label="是否检测到人脸"
            prop="hasFace"
            :formatter="formatBool"
          ></el-table-column>
          <el-table-column
            label="活体状态"
            prop="liveness"
            :formatter="formatLiveness"
          ></el-table-column>
          <el-table-column
            label="人脸质量"
            prop="isQualityPass"
            :formatter="formatBool"
          ></el-table-column>
        </el-table>
      </div>

      <!-- 操作按钮 -->
      <div class="btn-group" style="margin-top: 20px; text-align: center">
        <el-button type="primary" @click="startCamera">开启摄像头</el-button>
        <el-button type="success" @click="detectFace" :disabled="!cameraActive"
          >检测人脸</el-button
        >
        <el-button type="danger" @click="stopCamera" :disabled="!cameraActive"
          >关闭摄像头</el-button
        >
      </div>
    </el-card>
  </div>
</template>

<script>
import { faceDetect } from "@/api/system/face"; // 导入后端接口

export default {
  data() {
    return {
      cameraActive: false,
      videoStream: null,
      detectInfo: { hasFace: false, liveness: "UNKNOWN", isQualityPass: false },
      faceCanvas: null,
      canvasCtx: null,
    };
  },
  mounted() {
    // 初始化Canvas上下文
    this.faceCanvas = this.$refs.faceCanvas;
    this.canvasCtx = this.faceCanvas.getContext("2d");
  },
  methods: {
    // 开启摄像头
    startCamera() {
      navigator.mediaDevices
        .getUserMedia({ video: true })
        .then((stream) => {
          this.$refs.video.srcObject = stream;
          this.videoStream = stream;
          this.cameraActive = true;
        })
        .catch((err) => this.$message.error("摄像头开启失败：" + err.message));
    },

    // 关闭摄像头
    stopCamera() {
      if (this.videoStream) {
        this.videoStream.getTracks().forEach((track) => track.stop());
        this.cameraActive = false;
        this.clearFaceRect(); // 清除人脸框
      }
    },

    // 检测人脸并展示识别信息
    detectFace() {
      const video = this.$refs.video;
      const canvas = document.createElement("canvas");
      canvas.width = 400;
      canvas.height = 300;
      canvas.getContext("2d").drawImage(video, 0, 0, 400, 300);
      const imageBase64 = canvas.toDataURL("image/jpeg").split(",")[1];

      // 调用后端检测接口
      faceDetect({ imageBase64 }).then((res) => {
        if (res.code === 200) {
          this.detectInfo = res.data;
          this.drawFaceRect(res.data.faceLocation); // 绘制人脸框
          // 提示活体/质量问题
          if (res.data.liveness === "NOT_LIVE") {
            this.$message.warning("请确保是真人，非照片/视频");
          }
          if (!res.data.isQualityPass) {
            this.$message.warning("人脸模糊或有遮挡，请调整姿势");
          }
        } else {
          this.$message.error(res.msg);
        }
      });
    },

    // 绘制人脸框（根据识别到的位置坐标）
    drawFaceRect(location) {
      this.clearFaceRect(); // 先清除旧框
      if (!location) return;

      const ctx = this.canvasCtx;
      ctx.strokeStyle = "#409EFF"; // 蓝色边框
      ctx.lineWidth = 2;
      // 绘制矩形（left/top为百分比，需转成像素）
      const left = (location.left / 100) * 400;
      const top = (location.top / 100) * 300;
      const width = (location.width / 100) * 400;
      const height = (location.height / 100) * 300;
      ctx.strokeRect(left, top, width, height);
    },

    // 清除人脸框
    clearFaceRect() {
      this.canvasCtx.clearRect(0, 0, 400, 300);
    },

    // 格式化布尔值显示
    formatBool(row, column) {
      return row[column.prop] ? "是" : "否";
    },

    // 格式化活体状态显示
    formatLiveness(row) {
      const map = { LIVE: "活体", NOT_LIVE: "非活体", UNKNOWN: "未知" };
      return map[row.liveness] || "未知";
    },
  },
};
</script>
